/*
 * desc：请求封装：primi async await、请求拦截、响应拦截
 */

import axios from 'axios'
import { Message } from 'element-ui'
import store from './store.js'
import { getToken } from './auth.js'

const service = axios.create({
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
  baseURL:
    process.env.NODE_ENV === 'development'
      ? '/api'
      : process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 300000,
})

service.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response
    if (res.status != 200) {
      Message({ message: res.msg || 'Error', type: 'error' })
      if (res.code == 401 || res.code == 406) {
        Message({ message: '你的登录已过期，请重新登录', type: 'error' })
        setTimeout(() => {
          store.dispatch('pmsRemove').then(() => {
            location.reload()
          })
        }, 2000)
      }
      return res
    } else {
      return res
    }
  },
  (error) => {
    var res = error.response

    if (res?.status == 400) {
      Message({ message: res.data.message, type: 'error' })
      return res
    } else {
      if (res?.status == 401 || res?.status == 406) {
        Message({ message: '你的登录已过期，请重新登录', type: 'error' })
        setTimeout(() => {
          store.dispatch('pmsRemove').then(() => {
            location.reload()
          })
        }, 500)
      } else {
        Message({ message: res?.data?.message ?? '服务器错误', type: 'error' })
        return Promise.reject(error)
      }
      return Promise.reject(error)
    }
  }
)

function apiAxios(params) {
  const httpDefault = {
    responseType: params.responseType,
    method: params.method,
    url: params.url,
    params:
      params.method === 'GET' || params.method === 'get' ? params.data : null,
    data:
      params.method === 'POST' ||
      params.method === 'PUT' ||
      params.method === 'PATCH' ||
      params.method === 'patch' ||
      params.method === 'post' ||
      params.method === 'put'
        ? params.data
        : null,
  }
  return new Promise((resolve, reject) => {
    service(httpDefault)
      .then((res) => {
        resolve(res)
      })
      .catch((response) => {
        reject(response)
      })
  })
}
export default apiAxios
